package com.feizhou.oauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author Administrator
 * @version 1.0
 **/
@Configuration
@EnableResourceServer
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    // 令牌存储策略
    private TokenStore tokenStore;


    // 授权服务的资源列表
    public static final String RESOURCE_ID = "res1";
    
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                // 资源 id
                .resourceId(RESOURCE_ID)
//                // 令牌服务
//                .tokenServices(tokenService())
                // 令牌服务
                .tokenStore(tokenStore)
                .stateless(true);
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        
        http
                
                .authorizeRequests().antMatchers("/**")
                // 所有的访问,授权访问都要是all,和认证服务器的授权范围一一对应
                .access("#oauth2.hasScope('all')")
                //去掉防跨域攻击
                .and().csrf().disable()
                //session管理
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    
//    @Bean
//    // 资源服务令牌解析服务
//    public ResourceServerTokenServices tokenService() {
//        // 使用远程服务请求授权服务器校验token,必须指定校验token 的url、client_id，client_secret
//        RemoteTokenServices service = new RemoteTokenServices();
//        service.setCheckTokenEndpointUrl("http://localhost:8081/oauth/check_token");
//        service.setClientId("c1");
//        service.setClientSecret("secret");
//        return service;
//    }
    
}
